﻿using IdentityModel.Client;
using JuCheap.Core.Infrastructure;
using JuCheap.Core.Infrastructure.Exceptions;
using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Infrastructure.Utilities;
using JuCheap.Core.IService;
using JuCheap.Core.IService.AppService;
using JuCheap.Core.Model;
using JuCheap.Core.Model.Permission;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace JuCheap.Core.WebApi.Controllers
{
    /// <summary>
    /// 用户服务api
    /// </summary>
    [Route("api/[controller]")]
    public class UserController : BaseApiController
    {
        private readonly IConfiguration _configuration;
        private readonly ISysUserService _sysUserService;
        private readonly IUserService _userService;
        private readonly ICurrentUserService _currentUserService;

        /// <summary>
        /// ctor
        /// </summary>
        public UserController(IConfiguration configuration,
            ISysUserService sysUserService,
            IUserService userService,
            ICurrentUserService currentUserService)
        {
            _configuration = configuration;
            _sysUserService = sysUserService;
            _userService = userService;
            _currentUserService = currentUserService;
        }

        /// <summary>
        /// 登陆接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        [AllowAnonymous]
        public async Task<ActionResult<LoginResponseDto>> Login([FromBody]LoginRequestDto loginDto)
        {
            var identityServerUrl = _configuration.GetValue<string>("IdentityServerUrl");
            var apiId = _configuration.GetValue<string>("Api:Id");
            var apiSecret = _configuration.GetValue<string>("Api:Secret");

            //向IdentityServer请求令牌
            using (var tokenClient = new HttpClient())
            {
                var response = await tokenClient.RequestPasswordTokenAsync(new PasswordTokenRequest
                {
                    Address = $"{identityServerUrl}connect/token",
                    ClientId = apiId,
                    ClientSecret = apiSecret,
                    Scope = apiId,
                    UserName = loginDto.LoginAccount,
                    Password = loginDto.Password
                });

                if (response.IsError)
                {
                    throw new BusinessException(response.Error);
                }

                var tokenInfo = new LoginResponseDto
                {
                    Token = response.AccessToken,
                    Expire = response.ExpiresIn
                };

                return Ok(tokenInfo);
            }
        }

        /// <summary>
        /// 创建用户信息
        /// </summary>
        /// <param name="userCreateDto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("create")]
        public async Task<ActionResult<string>> Create([FromBody]UserCreateRequestDto userCreateDto)
        {
            var userId = await _userService.CreateAsync(userCreateDto);
            return Ok(userId);
        }

        /// <summary>
        /// 分页获取用户信息
        /// </summary>
        [HttpPost]
        [Route("search")]
        public async Task<ActionResult<PagedResult<SysUserDto>>> Search([FromBody]SysUserFilter filter)
        {
            var records = await _userService.QueryPagesAsync(filter);
            return Ok(records);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        [HttpGet]
        [Route("{id}")]
        public async Task<ActionResult<SysUserDto>> Get([FromRoute]string id)
        {
            var userDto = await _sysUserService.FindAsync(id);
            userDto.Password = userDto.SecurityKey = string.Empty;
            return Ok(userDto);
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userEditDto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("edit")]
        public async Task<ActionResult<bool>> Edit([FromBody]UserEditRequestDto userEditDto)
        {
            await _userService.UpdateAsync(userEditDto);
            return Ok(true);
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="ids">id集合</param>
        /// <returns></returns>
        [HttpPost]
        [Route("delete")]
        public async Task<ActionResult<bool>> Delete([FromBody]IList<string> ids)
        {
            if (!ids.AnyOne())
            {
                return NotFound();
            }
            if (await _sysUserService.ExistsAsync(x => ids.Contains(x.Id) && x.IsAdmin))
            {
                throw new BusinessException("管理员账号无法删除");
            }
            await _sysUserService.DeleteAsync(ids);
            return Ok(true);
        }

        /// <summary>
        /// 获取当前用户的基础信息和权限信息
        /// </summary>
        [HttpGet]
        [Route("my")]
        public ActionResult<UserPermissionResponseDto> GetUserInfoWithMenu()
        {
            var user = _currentUserService.GetCurrentUser();
            var json = new UserPermissionResponseDto
            {
                UserInfo = user
            };
            return Ok(json);
        }

        /// <summary>
        /// 获取当前用户的基础信息和权限信息
        /// </summary>
        [HttpGet]
        [Route("info")]
        public async Task<ActionResult<UserPermissionResponseDto>> GetUserInfoWithPermissions()
        {
            var user = _currentUserService.GetCurrentUser();
            var userMenuList = await _userService.GetUserMenusAsync(_currentUserService.GetUserId());
            
            //默认的示例页面的权限
            var permissions = new List<UserRolePermissionResponse>
            {
                new UserRolePermissionResponse("admin", "Introduce", "系统介绍"),
                new UserRolePermissionResponse("admin", "LoginLog", "登录日志"),
                new UserRolePermissionResponse("admin", "VisitLog", "访问日志"),
                new UserRolePermissionResponse("admin", "dashboard", "仪表盘"),
                new UserRolePermissionResponse("admin", "exception", "异常页面权限"),
                new UserRolePermissionResponse("admin", "result", "结果权限"),
                new UserRolePermissionResponse("admin", "profile", "详细页权限"),
                new UserRolePermissionResponse("admin", "table", "表格权限"),
                new UserRolePermissionResponse("admin", "form", "表单权限"),
                new UserRolePermissionResponse("admin", "order", "订单管理"),
                new UserRolePermissionResponse("admin", "permission", "权限管理"),
                new UserRolePermissionResponse("admin", "role", "角色管理"),
                new UserRolePermissionResponse("admin", "table", "桌子管理"),
                new UserRolePermissionResponse("admin", "user", "用户管理"),
                new UserRolePermissionResponse("admin", "support", "超级模块"),
            };

            //系统动态菜单权限
            foreach(var menu in userMenuList)
            {
                permissions.Add(new UserRolePermissionResponse("admin", menu.Id, menu.Name));
            }

            //用户基础信息
            var json = new UserInfoWithRoleResponse
            {
                Id = user.UserId,
                Name = user.Name,
                Username = user.LoginName,
                Password = "",
                Avatar = "https://gw.alipayobjects.com/zos/rmsportal/jZUIxmJycoymBprLOUbT.png",
                Status = 1,
                Telephone = "",
                LastLoginIp = "",
                LastLoginTime = DateTime.Now,
                CreatorId = "",
                CreateTime = DateTime.Now,
                Deleted = false,
                RoleId = "admin",
                Lang = "zh-CN",
                Token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""),
                Role = new UserRoleResponse
                {
                    Id = "admin",
                    Name = "管理员",
                    Describe = "拥有所有权限",
                    Status = 1,
                    Permissions = permissions
                }
            };
            return Ok(json);
        }

        /// <summary>
        /// 获取当前用户的菜单权限列表
        /// </summary>
        [HttpGet]
        [Route("my/menu")]
        public async Task<ActionResult<List<MenuResponseDto>>> GetMyMenues()
        {
            //添加默认的介绍页面，防止没有权限，前台跳转到404页面
            var workKey = "Introduce";
            var homeMenu = new MenuResponseDto
            {
                Key = workKey,
                Icon = "home",
                Title = "控制台",
                Value = workKey,
                Children = new List<MenuResponseDto>
                {
                    new MenuResponseDto
                    {
                        Icon = "right",
                        Key = workKey,
                        Path = "/dashboard/Introduce",
                        Selectable = false,
                        Title = "系统介绍",
                        Value = workKey,
                    },
                    new MenuResponseDto
                    {
                        Icon = "right",
                        Key = "LoginLog",
                        Path = "/dashboard/LoginLog",
                        Selectable = false,
                        Title = "登录日志",
                        Value = Guid.NewGuid().ToString("N"),
                    },
                    new MenuResponseDto
                    {
                        Icon = "right",
                        Key = "VisitLog",
                        Path = "/dashboard/VisitLog",
                        Selectable = false,
                        Title = "访问日志",
                        Value = Guid.NewGuid().ToString("N"),
                    }
                }
            };
            var responseList = new List<MenuResponseDto> { homeMenu };
            var dynamicMenus = await _userService.GetMenuTreeAsync(_currentUserService.GetUserId(), false, _currentUserService.IsSystemCompany());
            responseList.AddRange(dynamicMenus);
            return Ok(responseList);
        }

        /// <summary>
        /// 获取用户角色Id集合
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{userId}/roleids")]
        public async Task<ActionResult<IEnumerable<string>>> GetRoleIds([FromRoute]string userId)
        {
            var roleIds = await _userService.GetUserRoleIdsAysnc(userId);
            return Ok(roleIds);
        }

        /// <summary>
        /// 设置用户角色
        /// </summary>
        /// <param name="userRoleSetRequest">用户角色信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("set/role")]
        public async Task<ActionResult<bool>> SetRoleIds([FromBody]UserRoleSetRequestDto userRoleSetRequest)
        {
            await _userService.SetRolesAsync(userRoleSetRequest);
            return Ok(true);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="passwordDto">重置密码模型</param>
        /// <returns></returns>
        [HttpPost]
        [Route("changepassword")]
        public async Task<ActionResult<bool>> ChangePassword([FromBody]UserChangePasswordDto passwordDto)
        {
            passwordDto.Id = _currentUserService.GetUserId();
            var success = await _userService.ChangePasswordAsync(passwordDto);
            return Ok(success);
        }

        /// <summary>
        /// 基本资料获取
        /// </summary>
        /// <returns>用户基本资料信息</returns>
        [HttpGet]
        [Route("profile")]
        public async Task<ActionResult<UserProfileUpdateDto>> GetProfile()
        {
            var user = await _sysUserService.FindAsync(_currentUserService.GetUserId());
            var profile = new UserProfileUpdateDto
            {
                Name = user.Name,
                Email = user.Email,
                Phone = user.Phone,
                Motto = user.Motto
            };
            return Ok(profile);
        }

        /// <summary>
        /// 基本资料更新
        /// </summary>
        /// <param name="profile">基本资料</param>
        /// <returns></returns>
        [HttpPut]
        [Route("profile")]
        public async Task<ActionResult<bool>> UpdateProfile([FromBody]UserProfileUpdateDto profile)
        {
            profile.Id = _currentUserService.GetUserId();
            var success = await _userService.UpdateProfileAsync(profile);
            return Ok(success);
        }

        /// <summary>
        /// 判断用户是否拥有指定的权限
        /// </summary>
        /// <param name="permissionCode">权限唯一编码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("has/permission/{permissionCode}")]
        public async Task<ActionResult<bool>> HasPermission([FromRoute]string permissionCode)
        {
            if (_currentUserService.IsAdmin())
            {
                return Ok(true);
            }
            var hasPermission = await _userService.HasPermissionAsync(_currentUserService.GetUserId(), permissionCode);
            return Ok(hasPermission);
        }

        /// <summary>
        /// 获取近30日的访问量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("visit-datas")]
        public ActionResult GetVisitNumbers()
        {
            int length = 30;
            string[] days = new string[length];
            int[] dayNumbers = new int[length];
            int[] dayLineNumbers = new int[length];
            var today = DateTime.Now.Date;
            for(var i = 0; i < length; i++)
            {
                days[i] = today.AddDays(i - length).ToString("yyyy年MM月dd");

                dayNumbers[i] = new Random(Guid.NewGuid().GetHashCode()).Next(3000, 60000);

                dayLineNumbers[i] = dayNumbers[i] + new Random(Guid.NewGuid().GetHashCode()).Next(3000, 5000);
            }
            var json = new
            {
                days = days,
                dayNumbers = dayNumbers,
                dayLineNumbers = dayLineNumbers
            };
            return Ok(json);
        }
    }
}
